package com.dropdb.demo.controller.admin;

import com.dropdb.demo.bean.Admin;
import com.dropdb.demo.bean.enumeration.ErrorReason;
import com.dropdb.demo.bean.vo.BaseRespVO;
import com.dropdb.demo.service.AdminService;
import com.dropdb.demo.shiro.MallToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Date;
import java.util.Map;

/**
 * @author:tanxin Desc:
 * @date:2020/6/26 13:28
 */
@RestController
@RequestMapping("/admin/auth/")
public class AdminAuthController {
    @Autowired
    AdminService adminService;


    /**
     * 登录
     */
    @RequestMapping("login")
    public BaseRespVO login(@RequestBody Map map, HttpServletRequest request){
        Subject subject = SecurityUtils.getSubject();
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        subject.login(new MallToken(username, password, "admin"));
        // 登陆成功，更新登录时间和ip
        Admin admin = (Admin) subject.getPrincipal();
        String localAddr = request.getLocalAddr();
        admin.setLastLoginTime(new Date());
        admin.setLastLoginIp(localAddr);
        admin.setPassword(null); //避免错误地更新密码
        adminService.update(admin);
        Serializable id = subject.getSession().getId();
        return BaseRespVO.ok(id);
    }


    /**
     * 注销
     */
    @RequestMapping("logout")
    public BaseRespVO logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVO.ok();
    }

    @RequestMapping("info")
    public BaseRespVO info(String token){
        Subject subject = SecurityUtils.getSubject();
        Admin admin = (Admin) subject.getPrincipal();
        Map<String,Object> info = adminService.getLoginInfo(admin);
        return BaseRespVO.ok(info);
    }


    @RequestMapping("unauthc")
    public BaseRespVO unauthc() {
        return BaseRespVO.error(ErrorReason.UN_LOGIN.getCode(), ErrorReason.UN_LOGIN.getReason());
    }
}
